package com.dailywork.basepro.xml;

import com.dailywork.basepro.xml.model.Book;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * @author think
 * @version 2019/10/20
 * @since DOM4J解析xml文件
 */
public class ReadXMLByDom4j {

    private List<Book> bookList = null;

    public List<Book> getBooks(File file) {

        SAXReader reader = new SAXReader();
        try {
            Document document = reader.read(file);
            Element bookstore = document.getRootElement();
            Iterator storeit = bookstore.elementIterator();

            bookList = new ArrayList<>();
            while (storeit.hasNext()) {
                Book book = new Book();
                Element bookElement = (Element) storeit.next();
                // 遍历bookElement的属性
                List<Attribute> attributes = bookElement.attributes();
                for (Attribute attribute : attributes) {
                    if ("id".equals(attribute.getName())) {
                        String id = attribute.getValue();
                        book.setId(Integer.parseInt(id));
                    }
                }

                Iterator bookit = bookElement.elementIterator();
                while (bookit.hasNext()) {
                    Element child = (Element) bookit.next();
                    String nodeName = child.getName();
                    if ("name".equals(nodeName)) {
                        String name = child.getStringValue();
                        book.setName(name);
                    } else if ("author".equals(nodeName)) {
                        String author = child.getStringValue();
                        book.setAuthor(author);
                    } else if ("year".equals(nodeName)) {
                        String year = child.getStringValue();
                        book.setYear(Integer.parseInt(year));
                    } else if ("price".equals(nodeName)) {
                        String price = child.getStringValue();
                        book.setPrice(Double.parseDouble(price));
                    }
                }
                bookList.add(book);
                book = null;
            }
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        return bookList;
    }

    public static void main(String[] args) {
        File file = new File("src/res/books.xml");
        List<Book> bookList = new ReadXMLByDom4j().getBooks(file);
        for (Book book : bookList) {
            System.out.println(book);
        }
    }
}
